package com.fanrui.code.config;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.reflections.ReflectionUtils;

import com.fanrui.code.configfile.LoadConfigFile;
import com.fanrui.code.db.jvmdb.IPersistable;
import com.fanrui.code.util.SessionUtil;

public class ConfigFileManager extends LoadConfigFile<Integer, IPersistable<Integer>> {

	// singleton
	protected ConfigFileManager() {
		super("com.fanrui.code.entity");
	}
	
	private static class singleton {
		private static ConfigFileManager instance = new ConfigFileManager();
	}
	
	public static ConfigFileManager getInstance() {
		return singleton.instance;
	}

	@Override
	public Map<Integer, IPersistable<Integer>> loadConfigFile(String configFileName) {
		Class<?> clazz = ReflectionUtils.forName(configFileName+"Mapper");
		SqlSession session = SessionUtil.getSession();
		Object obj = session.getMapper(clazz);
		try {
			Method loadConfigFileMethod = clazz.getMethod("selectAllItem");
			@SuppressWarnings("unchecked")
			List<IPersistable<Integer>> list = (List<IPersistable<Integer>>) loadConfigFileMethod.invoke(obj);
			if(list != null && !list.isEmpty()) {
				Map<Integer, IPersistable<Integer>> result = new HashMap<Integer, IPersistable<Integer>>();
				for(IPersistable<Integer> iPersistable : list) {
					result.put(iPersistable.getPersistKey(), iPersistable);
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
